package com.hyh.admin.tool;


import org.springframework.stereotype.Component;

/**
 * 雪花算法生成器
 * @date 2024/5/26 16:23
 */
public class SnowflakeIdGeneratorUtil {
    private final Long twepoch = 1288834974657L;
    private final Long workerIdBits = 5L;
    private final Long datacenterIdBits = 5L;
    private final Long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private final Long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    private final Long sequenceBits = 12L;
    private final Long workerIdShift = sequenceBits;
    private final Long datacenterIdShift = sequenceBits + workerIdBits;
    private final Long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private final Long sequenceMask = -1L ^ (-1L << sequenceBits);
    private Long workerId;
    private Long datacenterId;
    private Long sequence = 0L;
    private Long lastTimestamp = -1L;

    /**
     * 构造函数
     * @param  workerId
     * @param  datacenterId
     */

    public SnowflakeIdGeneratorUtil(Long workerId, Long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }


    /**
     * 生成雪花ID
     */
    public synchronized Long nextId() {
        Long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    protected Long tilNextMillis(Long lastTimestamp) {
        Long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected Long timeGen() {
        return System.currentTimeMillis();
    }
}
